﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008, 2009 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using EngineOfEvermore.Common;

namespace EngineOfEvermore.Scene.Visual
{
    public abstract class AbstractSprite : VisualComponentChild
    {
        #region Variables
        Vector2d _positionOffset;
        Vector2d _worldPosition;
        float _rotationOffset;
        float _worldRotation;
        Vector2d _scale = new Vector2d( 1, 1 );
        Vector2d _originalSize;
        Vector2d _scaledSize;
        float _sortingOffsetY;

        bool _flipX;
        bool _flipY;
        
        readonly Vector2d[] _worldVertexBuffer = new Vector2d[4];
        
        RectangleF _clipArea = new RectangleF( 0.0f, 0.0f, 1.0f, 1.0f );
        #endregion

        #region Properties
        public Vector2d PositionOffset
        {
            get { return _positionOffset; }
            set 
            { 
                _positionOffset = value;
                _updateSpatials();
            }
        }

        public float RotationOffset
        {
            get { return _rotationOffset; }
            set 
            { 
                _rotationOffset = value;
                _updateSpatials();
            }
        }

        public Vector2d Scale
        {
            get { return _scale; }
            set 
            { 
                _scale = value;
                _scaledSize.X = _originalSize.X * _scale.X;
                _scaledSize.Y = _originalSize.Y * _scale.Y;
                _updateSpatials();
            }
        }

        public bool FlipX
        {
            get { return _flipX; }
            set { _flipX = value; }
        }

        public bool FlipY
        {
            get { return _flipY; }
            set { _flipY = value; }
        }

        public RectangleF ClipArea
        {
            get { return _clipArea; }
            set 
            {
                _clipArea = value;

                if ( _clipArea.X.EpsilonIsZero() &&
                     _clipArea.Y.EpsilonIsZero() &&
                     _clipArea.Width.EpsilonEquals( 1.0f ) &&
                     _clipArea.Height.EpsilonEquals( 1.0f )
                    )
                {
                    _clippingActive = false;
                }
                else
                {
                    _clippingActive = true;
                }
            }
        }

        [SerializerIgnore]
        public Vector2d OriginalSize
        {
            get { return _originalSize; }
            protected set
            {
                _originalSize = value;
                _scaledSize.X = _originalSize.X * _scale.X;
                _scaledSize.Y = _originalSize.Y * _scale.Y;
                _updateSpatials();
            }
        }

        public Vector2d ScaledSize
        {
            get { return _scaledSize; }
        }

        public float SortingOffsetY
        {
            get { return _sortingOffsetY; }
            set 
            {
                _sortingOffsetY = value;
                _yRefValue = _worldPosition.Y + _sortingOffsetY;
            }
        }

        public Vector2d WorldPosition
        {
            get { return _worldPosition; }
        }

        public float WorldRotation
        {
            get { return _worldRotation; }
        }

        protected Vector2d[] _worldVertices 
        {
            get { return _worldVertexBuffer; }
        }

        protected bool _clippingActive
        {
            get;
            private set;
        }

        protected bool _isRotated
        {
            get;
            private set;
        }
        #endregion

        #region Constructor
        protected AbstractSprite() :
            base( true )
        { 
        }
        #endregion

        #region Methods
        public override void Update( LogicUpdateEventArgs e )
        {
 	         base.Update(e);
             _updateSpatials();
        }

        void _updateSpatials()
        {
            if ( Owner != null )
            {
                Vector2d worldPosition = this.Owner.GetWorldPosition( _positionOffset );
                float worldRotation = this.Owner.WorldRotation + _rotationOffset;

                if ( worldPosition.EpsilonEquals( _worldPosition ) &&
                     worldRotation.EpsilonEquals( _worldRotation ) &&
                     _aabb.Width.EpsilonEquals( _scaledSize.X ) &&
                     _aabb.Height.EpsilonEquals( _scaledSize.Y ) )
                {
                    return;
                }
                else
                {
                    _worldPosition = worldPosition;
                    _worldRotation = worldRotation;
                }
            }
            else
            {
                _worldPosition = _positionOffset;
                _worldRotation = _rotationOffset;
            }

            _yRefValue = _worldPosition.Y + _sortingOffsetY;
            
            #warning The rest of the function only works for symmetric sprites! 
            if ( _worldRotation.EpsilonIsZero() )
            {
                Vector2d halfSize = _scaledSize * 0.5f;

                _aabb.X = _worldPosition.X - halfSize.X;
                _aabb.Y = _worldPosition.Y - halfSize.Y;
                _aabb.Width = _scaledSize.X;
                _aabb.Height = _scaledSize.Y;

                _worldVertexBuffer[0].X = _worldPosition.X - halfSize.X;
                _worldVertexBuffer[0].Y = _worldPosition.Y - halfSize.Y;

                _worldVertexBuffer[1].X = _worldPosition.X + halfSize.X;
                _worldVertexBuffer[1].Y = _worldPosition.Y - halfSize.Y;
                
                _worldVertexBuffer[2].X = _worldPosition.X + halfSize.X;
                _worldVertexBuffer[2].Y = _worldPosition.Y + halfSize.Y;
                
                _worldVertexBuffer[3].X = _worldPosition.X - halfSize.X;
                _worldVertexBuffer[3].Y = _worldPosition.Y + halfSize.Y;

                _isRotated = false;
            }
            else
            {
                float sin = (float) Math.Sin( _worldRotation );
                float cos = (float) Math.Cos( _worldRotation );

                Vector2d halfWidth = new Vector2d( _scaledSize.X * 0.5f, 0.0f );
                halfWidth.Rotate( sin, cos );

                Vector2d halfHeight = new Vector2d( 0.0f, _scaledSize.Y * 0.5f );
                halfHeight.Rotate( sin, cos );

                _worldVertexBuffer[0] = _worldPosition - halfWidth - halfHeight;
                _worldVertexBuffer[1] = _worldPosition + halfWidth - halfHeight;
                _worldVertexBuffer[2] = _worldPosition + halfWidth + halfHeight;
                _worldVertexBuffer[3] = _worldPosition - halfWidth + halfHeight;

                float minX;
                float maxX;
                float minY;
                float maxY;

                _worldVertexBuffer.Select( v => v.X ).FindMinMax( out minX, out maxX );
                _worldVertexBuffer.Select( v => v.Y ).FindMinMax( out minY, out maxY );

                _aabb.X = minX;
                _aabb.Y = minY;
                _aabb.Width = maxX - minX;
                _aabb.Height = maxY - minY;

                _isRotated = true;
            }
        }

        protected void _copyAbstractSpriteStateTo( AbstractSprite sprite )
        {
            sprite._clipArea = _clipArea;
            sprite._flipX = _flipX;
            sprite._flipY = _flipY;
            sprite._positionOffset = _positionOffset;
            sprite._rotationOffset = _rotationOffset;
            sprite._scale = _scale;
            sprite._sortingOffsetY = _sortingOffsetY;
            sprite._intraSpaceLayer = _intraSpaceLayer;
            sprite._originalSize = _originalSize;
            sprite._scaledSize = _scaledSize;

            sprite.Update( null );
        }
        #endregion
    }
}
